﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using Model;

namespace ACM
{
    public partial class SaleKeyIn1 : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //Reset Page
                hdfTXId.Value = BusinessID.ToString();
                lnkAttack.NavigateUrl = "";

                if (BusinessID != 0)
                {
                    LoadValueForEdit(BusinessID);
                }
            }
        }

        private void LoadValueForEdit(int id)
        {
            GetACMTXCommand cmd = new GetACMTXCommand(id);
            cmd.Execute();

            if (cmd.Result.Count > 0)
            {
                acm_tx tx = cmd.Result[0];

                //Visible UI
                txtVIN.Text = tx.vin;
                txtSaleDate.Text = tx.adv_date.Value.ToString("dd/MM/yyyy");
                txtDeliveryDate.Text = (tx.dlv_date != null) ? tx.dlv_date.Value.ToString("dd/MM/yyyy") : "";
                txtCustomerName.Text = tx.customer_name;
                txtIdCard.Text = tx.id_card;
                txtAddressNo.Text = tx.addr_no;
                txtVillageName.Text = tx.village;
                txtGroupNo.Text = tx.group_no;
                txtAlleyName.Text = tx.alley;
                txtBuildingName.Text = tx.building_name;
                txtRoomNo.Text = tx.room_no;
                txtFloor.Text = tx.floor_no;
                txtRoad.Text = tx.road_name;
                txtParish.Text = tx.parish;
                txtDistrict.Text = tx.district;
                txtProvince.Text = tx.province;
                txtPostCode.Text = tx.postcode;

                GetSalesCampaignList(tx.adv_date.Value, tx.car_series_id.Value);
                ddlSaleCampaign.SelectedValue = tx.campaign_id_adv.Value.ToString();

                if (tx.dlv_date != null)
                {
                    GetDeliveryCampaignList(tx.dlv_date.Value, tx.car_series_id.Value);
                    ddlDeliveryCampaign.SelectedValue = tx.campaign_id_dlv.Value.ToString();
                    CalculateDiffAmount(tx.dlv_date.Value, tx.car_series_id.Value);
                }

                if (tx.mobile_note4 == 1)
                    rbMobile.Checked = true;
                else
                    rbMoney.Checked = true;

                if (tx.attach1 != "" && tx.attach1 != null)
                {
                    lnkAttack.Visible = true;
                    lblAttachFileName.Text = tx.attach1;

                    lnkAttack.NavigateUrl = ConfigurationManager.AppSettings["UploadPath"] + tx.attach1;
                    string Extension = Path.GetExtension(lnkAttack.NavigateUrl).ToLower();
                    if (Extension == ".png" || Extension == ".jpg" || Extension == ".jpeg")
                    {
                        lnkAttack.CssClass = "modalImage";
                        lnkAttack.Attributes.Add("data-effect", "mfp-zoom-in");
                    }
                    else
                    {
                        lnkAttack.Attributes.Add("target", "_blank");
                    }
                }

                chkPassport.Checked = tx.passport != null ? tx.passport.Value : false;

                //Invisible UI
                hdfSeriesId.Value = tx.car_series_id.ToString();
                hdfTXId.Value = tx.id.ToString();

                pnlKeyIn.Enabled = true;
                FileUpload1.Enabled = true;
                btnSave.Enabled = true;
                Status.Hide();
            }
        }

        protected void GetSalesCampaignList(DateTime dt, int series_id)
        {
            GetCampaignCommand cmd = new GetCampaignCommand(dt, series_id);
            cmd.Execute();

            ddlSaleCampaign.DataSource = cmd.Result;
            ddlSaleCampaign.DataValueField = "id";
            ddlSaleCampaign.DataTextField = "promotion_amount";
            ddlSaleCampaign.DataBind();
        }

        protected void GetDeliveryCampaignList(DateTime dt, int series_id)
        {
            GetCampaignCommand cmd = new GetCampaignCommand(dt, series_id);
            cmd.Execute();

            ddlDeliveryCampaign.DataSource = cmd.Result;
            ddlDeliveryCampaign.DataValueField = "id";
            ddlDeliveryCampaign.DataTextField = "promotion_amount";
            ddlDeliveryCampaign.DataBind();
        }

        protected int GetCarSerieId(string series, string sub_series, string suffix)
        {
            GetCarSeriesCommand cmd = new GetCarSeriesCommand(series, sub_series, suffix);
            cmd.Execute();
            if (cmd.Result != null)
                return cmd.Result.id;

            return 0;   //Nothing
        }


        protected void lnkCheckVIN_Click(object sender, EventArgs e)
        {
            GetCarAdvanceCommand cmd = new GetCarAdvanceCommand(txtVIN.Text); //Check Vin
            try
            {
                cmd.Execute();
            }
            catch (Exception ex)
            {
                string msg = "Try 1 " + ex.ToString();
                Status.ShowWarning(msg);
            }

            if (cmd.Result.Count > 0)
            {
                if (NotExistInTX(cmd.Result[0].vin))
                {

                    ClearForm();

                    if (cmd.Result[0].dealer_code != null && cmd.Result[0].dealer_code != "")
                    {
                        if (cmd.Result[0].dealer_code == CurrentUser.dealer_code) //Can Key
                        {
                            try
                            {
                                txtSaleDate.Text = cmd.Result[0].sale_date.ToString("dd-MM-yyyy");
                                hdfOwnerTX.Value = cmd.Result[0].dealer_code;
                                int serieId = GetCarSerieId(cmd.Result[0].car_series, cmd.Result[0].car_sub_series, cmd.Result[0].car_model_suffix);
                                hdfSeriesId.Value = serieId.ToString();

                                pnlKeyIn.Enabled = true;
                                FileUpload1.Enabled = true;
                                btnSave.Enabled = true;
                                Status.Hide();
                                btnSendRequest.Visible = false;

                                GetSalesCampaignList(cmd.Result[0].sale_date, serieId);
                            }
                            catch (Exception ex)
                            {
                                string msg = "Try 2 " + ex.ToString();
                                Status.ShowWarning(msg);
                            }

                        }
                        else
                        {
                            txtSaleDate.Text = cmd.Result[0].sale_date.ToString("dd-MM-yyyy");
                            hdfOwnerTX.Value = cmd.Result[0].dealer_code;
                            int serieId = GetCarSerieId(cmd.Result[0].car_series, cmd.Result[0].car_sub_series, cmd.Result[0].car_model_suffix);
                            hdfSeriesId.Value = serieId.ToString();

                            btnSave.Enabled = false;
                            string msg = "VIN ดังกล่าวถูกลงทะเบียนแล้ว ";

                            GetUserCommand ucmd = new GetUserCommand(cmd.Result[0].user_id);
                            ucmd.Execute();
                            if (ucmd.Result != null)
                            {
                                msg += "โดย " + ucmd.Result.dealer_name;
                            }

                            Status.ShowWarning(msg);
                            hdfOwnerTX.Value = cmd.Result[0].dealer_code;   //Store owner code
                            btnSendRequest.Visible = true;

                            if (Requested(txtVIN.Text, CurrentUser.dealer_code))
                            {
                                btnSendRequest.Visible = false;
                                Status.ShowWarning("รอการอนุมัติขอเปลี่ยนตัวแทนจำหน่าย");
                            }

                            pnlKeyIn.Enabled = false;
                            FileUpload1.Enabled = false;
                            btnSave.Enabled = false;
                        }
                    }
                    else
                    {
                        //Status.ShowError("VIN ดังกล่าว ยังไม่ได้ถูกลงทะเบียน");
                        //btnSendRequest.Visible = false;
                        //pnlKeyIn.Enabled = false;
                        //FileUpload1.Enabled = false;
                        //btnSave.Enabled = false;

                        txtSaleDate.Text = cmd.Result[0].sale_date.ToString("dd/MM/yyyy");
                        hdfOwnerTX.Value = CurrentUser.dealer_code; //Stored Current dealer instead
                        int serieId = GetCarSerieId(cmd.Result[0].car_series, cmd.Result[0].car_sub_series, cmd.Result[0].car_model_suffix);
                        hdfSeriesId.Value = serieId.ToString();

                        pnlKeyIn.Enabled = true;
                        FileUpload1.Enabled = true;
                        btnSave.Enabled = true;
                        Status.Hide();
                        btnSendRequest.Visible = false;

                        GetSalesCampaignList(cmd.Result[0].sale_date, serieId);

                        //[Back to store current user into part I]
                    }
                }
                else
                {
                    Status.ShowError("VIN ดังกล่าวได้ถูกลงทะเบียน Car Advance ไปแล้ว");
                    pnlKeyIn.Enabled = false;
                    FileUpload1.Enabled = false;
                    btnSave.Enabled = false;
                    ClearForm();
                    btnSendRequest.Visible = false;
                }
            }
            else
            {
                Status.ShowError("ไม่พบข้อมูลของ VIN ดังกล่าว");
                btnSendRequest.Visible = false;
                pnlKeyIn.Enabled = false;
                FileUpload1.Enabled = false;
                btnSave.Enabled = false;
            }
        }

        private bool NotExistInTX(string p)
        {
            GetACMTXCommand cmd = new GetACMTXCommand(p);
            cmd.Execute();

            return cmd.Result.Count == 0;
        }

        private bool Requested(string vin, string dealerCode)
        {
            CheckRequestedCommand cmd = new CheckRequestedCommand(vin, dealerCode);
            cmd.Execute();

            return (bool)cmd.Result;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string FileName = "";
            int TimeZoneDiff = Convert.ToInt32(ConfigurationManager.AppSettings["TimeZoneDiff"].ToString());

            if (lblAttachFileName.Text == "")
            {
                if (FileUpload1.HasFile)
                {
                    FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                    string FileNames = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);
                    string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();

                    if (Extension != ".jpg" && Extension != ".jpeg" && Extension != ".png" && Extension != ".pdf")
                    {
                        Status.ShowError("Upload File ผิดประเภท");
                        return;
                    }

                    string FolderPath = ConfigurationManager.AppSettings["UploadPath"];

                    FileName = FileNames + DateTime.Now.AddHours(TimeZoneDiff).ToString("_yyyymmdd_hhmmss") + Extension;
                    string FilePath = Server.MapPath(FolderPath + FileName);

                    FileUpload1.SaveAs(FilePath);
                }
                else
                {
                    Status.ShowError("กรุณาแนบไฟล์ก่อน");
                    return;
                }
            }
            else
            {
                if (FileUpload1.HasFile)
                {
                    FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                    string FileNames = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);
                    string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();

                    if (Extension != ".jpg" && Extension != ".jpeg" && Extension != ".png" && Extension != ".pdf")
                    {
                        Status.ShowError("Upload File ผิดประเภท");
                        return;
                    }

                    string FolderPath = ConfigurationManager.AppSettings["UploadPath"];

                    FileName = FileNames + DateTime.Now.AddHours(TimeZoneDiff).ToString("_yyyymmdd_hhmmss") + Extension;
                    string FilePath = Server.MapPath(FolderPath + FileName);

                    FileUpload1.SaveAs(FilePath);
                }
            }

            Status.Hide();

            acm_tx tx = new acm_tx();
            
            //From UI
            tx.id = hdfTXId.Value != "" ? Convert.ToInt32(hdfTXId.Value) : 0;
            tx.vin = txtVIN.Text;
            tx.adv_date = UIHelper.GetDateFromUI(txtSaleDate.Text);
            tx.dlv_date = UIHelper.GetDateFromUI(txtDeliveryDate.Text);
            tx.customer_name = txtCustomerName.Text;
            tx.id_card = txtIdCard.Text;
            tx.addr_no = txtAddressNo.Text;
            tx.village = txtVillageName.Text;
            tx.group_no = txtGroupNo.Text;
            tx.alley = txtAlleyName.Text;
            tx.building_name = txtBuildingName.Text;
            tx.room_no = txtRoomNo.Text;
            tx.floor_no = txtFloor.Text;
            tx.road_name = txtRoad.Text;
            tx.parish = txtParish.Text;
            tx.district = txtDistrict.Text;
            tx.province = txtProvince.Text;
            tx.postcode = txtPostCode.Text;
            if (ddlSaleCampaign.SelectedValue != "")
                tx.campaign_id_adv = Convert.ToInt32(ddlSaleCampaign.SelectedValue);
            else
                tx.campaign_id_adv = 0;
            if (ddlDeliveryCampaign.SelectedValue != "")
                tx.campaign_id_dlv = Convert.ToInt32(ddlDeliveryCampaign.SelectedValue);
            else
                tx.campaign_id_dlv = 0;
            if (FileUpload1.HasFile)
            {
                if (lnkAttack.NavigateUrl != "")    //Delete Old file
                {
                    string physFile = Server.MapPath(lnkAttack.NavigateUrl);
                    if (File.Exists(physFile))
                        File.Delete(physFile);
                }

                tx.attach1 = FileName;
                tx.attach1_date = DateTime.Now.AddHours(TimeZoneDiff);
            }

            //Invisible
            tx.sales_id = CurrentUser.id;
            tx.car_series_id = Convert.ToInt32(hdfSeriesId.Value);

            tx.adv_promotion_amount = (tx.campaign_id_adv != 0 && tx.campaign_id_adv != null) ? GetCampaign(tx.campaign_id_adv.Value).promotion_amount : 0;
            tx.dlv_promotion_amount = (tx.campaign_id_dlv != 0 && tx.campaign_id_dlv != null) ? GetCampaign(tx.campaign_id_dlv.Value).promotion_amount : 0;

            if (rbMoney.Checked || lblNoSpecial.Visible) //No Special or No select Special
            {
                //tx.diff_promotion_amount = tx.dlv_promotion_amount - tx.adv_promotion_amount;
                //if (tx.diff_promotion_amount < 0) tx.diff_promotion_amount = 0;
                tx.mobile_note4 = 0;
            }
            else
            {
                //tx.diff_promotion_amount = tx.dlv_promotion_amount - tx.adv_promotion_amount;
                //if (tx.diff_promotion_amount >= 0) tx.diff_promotion_amount = 0;
                tx.mobile_note4 = 1;
            }

            tx.campaign_with_note4 = lblNoSpecial.Visible ? 0 : 1;

            CalculateSumCommand cmd2 = new CalculateSumCommand(tx.campaign_id_adv.Value, tx.campaign_id_dlv.Value, tx.mobile_note4.Value, tx.campaign_with_note4.Value);
            cmd2.Execute();
            tx.diff_promotion_amount = Convert.ToDecimal(cmd2.Result);

            tx.tx_status = "ตรวจสอบเอกสาร";
            tx.tx_date = DateTime.Now.AddHours(TimeZoneDiff);
            tx.tx_dealer_code = CurrentUser.dealer_code;
            tx.passport = chkPassport.Checked;

            MaintainTransaction cmd = new MaintainTransaction(tx);
            cmd.Execute();

            Response.Redirect("VerifyTx.aspx?id=" + cmd.Result.ToString());
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        protected void ClearForm()
        {
            txtDeliveryDate.Text = "";
            txtCustomerName.Text = "";
            txtIdCard.Text = "";
            txtAddressNo.Text = "";
            txtVillageName.Text = "";
            txtGroupNo.Text = "";
            txtAlleyName.Text = "";
            txtBuildingName.Text = "";
            txtRoomNo.Text = "";
            txtFloor.Text = "";
            txtRoad.Text = "";
            txtParish.Text = "";
            txtDistrict.Text = "";
            txtProvince.Text = "";
            txtPostCode.Text = "";
            lblDiff.Text = "0 บาท";

            if (ddlSaleCampaign.Items.Count > 0)
            {
                ddlSaleCampaign.SelectedIndex = -1;
            }

            if (ddlDeliveryCampaign.Items.Count > 0)
            {
                ddlDeliveryCampaign.SelectedIndex = -1;
            }

            if (FileUpload1.HasFile)
            {
                FileUpload1.Attributes.Clear();
            }
        }

        protected void txtDeliveryDate_TextChanged(object sender, EventArgs e)
        {
            DateTime dt = UIHelper.GetDateFromUI(txtDeliveryDate.Text);
            DateTime sdt = UIHelper.GetDateFromUI(txtSaleDate.Text);

            if (DateTime.Compare(sdt, dt) <= 0)
            {
                GetDeliveryCampaignList(dt, Convert.ToInt32(hdfSeriesId.Value));
                CalculateDiffAmount(dt, Convert.ToInt32(hdfSeriesId.Value));
            }
            else
            {
                txtDeliveryDate.Text = "";
                Status.ShowError("กรุณาระบุวันที่ส่งมอบให้ถูกต้อง");
                //ScriptManager.RegisterStartupScript(this, this.GetType(), "ErrorDate", "alert('กรุณาระบุวันที่ส่งมอบให้ถูกต้อง');", true);
            }
        }

        protected acm_campaign GetCampaign(int id)
        {
            GetCampaignCommand cmd = new GetCampaignCommand(id);
            cmd.Execute();

            return cmd.Result.Count > 0 ? cmd.Result[0] : null;
        }

        protected void btnSendRequest_Click(object sender, EventArgs e)
        {
            MainTainRequestCommand cmd = new MainTainRequestCommand(txtVIN.Text, UIHelper.GetDateFromUI(txtSaleDate.Text), CurrentUser.dealer_code, hdfOwnerTX.Value, Convert.ToInt32(hdfSeriesId.Value));
            cmd.Execute();
            if ((int)cmd.Result != 0)
            {
                Response.Redirect("ChangeRequest.aspx?stat=succ_req");
            }
            else
            {
                Status.ShowError("ส่งคำร้องขอไม่สำเร็จ");
            }
        }

        protected void ddlSaleCampaign_SelectedIndexChanged(object sender, EventArgs e)
        {
            DateTime dt = UIHelper.GetDateFromUI(txtSaleDate.Text);
            CalculateDiffAmount(dt, Convert.ToInt32(hdfSeriesId.Value));
        }

        protected void ddlDeliveryCampaign_SelectedIndexChanged(object sender, EventArgs e)
        {
            DateTime dt = UIHelper.GetDateFromUI(txtDeliveryDate.Text);
            CalculateDiffAmount(dt, Convert.ToInt32(hdfSeriesId.Value));
        }

        protected void CalculateDiffAmount(DateTime dt, int series_id)
        {
            decimal amt = 0;
            acm_campaign delivery;
            acm_campaign sale;

            if (ddlDeliveryCampaign.SelectedIndex != -1)
            {
                delivery = GetCampaign(Convert.ToInt32(ddlDeliveryCampaign.SelectedValue));
                amt = (delivery.promotion_amount != null) ? delivery.promotion_amount.Value : 0;
            }

            if (ddlSaleCampaign.SelectedIndex != -1)
            {
                sale = GetCampaign(Convert.ToInt32(ddlSaleCampaign.SelectedValue));
                amt -= (sale.promotion_amount != null) ? sale.promotion_amount.Value : 0;
            }
            

            lblDiff.Text = String.Format("{0:n0} บาท", amt);
               

            GetSpecialCampaign cmd2 = new GetSpecialCampaign(dt, series_id, 1);
            cmd2.Execute();


            if (cmd2.Result.Count > 0)
            {
                sectionNote4.Text = "รับ " + cmd2.Result[0].campaign_name;
            }

            Note4SectionVisible = (cmd2.Result.Count > 0);

            return;           
        }

        public bool Note4SectionVisible
        {
            set
            {
                hintNote4.Visible = value;
                lblOr.Visible = value;
                sectionNote4.Visible = value;
                rbMobile.Visible = value;
                rbMoney.Visible = value;
                lblNoSpecial.Visible = !value;
            }
        }
    }
}